<?
/* ------------------ dbObject library --------------------------
   -------------------v. 0.2 (10-05-2005)------------------------
   -------------Created by Nekrasov Alex 2005--------------------
*/
   class dbObject{
   var $profile=array();   // v���ᨢ ������ � ��஬ �ଠ�
   var $id=0;
   var $db=null;
   var $err="";
   var $table="";
   var $filter="";
   var $read_only=array();
	
   function dbObject($db,$table,$id="",$filter="",$read_only=array()){
    $this->id=$id;
    $this->db=$db;
    $this->table=$table;
    $this->filter=$filter;
    $this->err="";
    $this->read_only=$read_only;

    if($this->id!=""||$this->filter!=""){
     $this->loadData();
    }
   }

   function loadData(){
   	
    $db=$this->db;
    $flds=$db->getFieldList($this->table);
    /***/
    $items = array();
    foreach($flds as $f=>$field){
    	if($f == 'key') continue;
    	if($field['Type'] == 'blob'){ // if field type is 'blob' then field has been encrypted with AES-algorithm 
    		$items[] = " AES_DECRYPT(`{$f}`,'{$db->AES_key}') as `{$f}` ";
    	}else{
    		$items[] = "`{$f}`";
    	}
    	$fields = implode(', ',$items);
    }
    
    /***/
    if($this->id!=''){
     $sql="SELECT {$fields} FROM ".$this->table." WHERE {$flds['key']['Field']}='{$this->id}' LIMIT 1";
    }
    elseif($this->filter!=''){
     $sql="SELECT {$fields} FROM ".$this->table." WHERE 1=1 {$this->filter} LIMIT 1";
    }
   $db->query($sql);
        if ($db->next_record()){
            $this->profile=$db->Record;
            if($this->id==''&&$this->filter!=''){
                $this->id=$this->profile[$flds['key']['Field']];
            }
            return true;
        }
        else{
            $err="Object was not found";
            return false;
        }
   }

   function saveData($data=""){
    $db=$this->db;
    //parsing out all read only fields
    if($data){
     $this->profile = $data;
    }
    foreach($this->read_only as $v){
     if(isset($this->profile[$v])) unset($this->profile[$v]);
    }
    $db->putRow($this->table,$this->profile,$this->id);

    if(!$this->id){
     $this->id=$db->last_id();
    }
    $this->loadData();
   }

   function remove(){
    $db=$this->db;
    $flds=$db->getFieldList($this->table);

    $sql="DELETE FROM ".$this->table." WHERE  {$flds['key']['Field']}='{$this->id}'";
    $db->query($sql);
   }

   function dump(){
    print_r($this->profile);
   }
  }
?>